#pragma once

#include "../node/node.h"
#include <unordered_map>

OPEN_JLIB_NS


struct EventManager {

  static constexpr s64 RenderPriority = 0x7FFFFFFFFFFFFFFFL;

  using handler_t = std::function<bool(Node*)>;

  struct Entry {
    List joint;
    Ptr<Node> node;
    s64 priority;
  };

  inline explicit EventManager (Node *root) noexcept : _root(root) {}

  inline void invalidate () noexcept { _dirty = true; }

  bool add (Node *node, s64 priority) noexcept;
  bool remove (Node *node);
  void clear ();
  void reorder () noexcept;

private:
  inline s64 computeDepth (Node *node) noexcept {
    for (s64 i = 0; node; ++i) {
      if (node == _root)
        return i;
    }
    return -1;
  }

protected:
  std::unordered_map<Node*, Entry> _map;
  List _queue = nullptr;
  Node *_root;
  bool _dirty = false;

  friend class KeyManager;
};


CLOSE_JLIB_NS